<template>
    <div>
        <el-alert v-if="!props.hideAlter" :closable="false" :type="state.disable?'error':'success'" show-icon style="height: 32px;margin-bottom: 8px">
            <template #title>
                <div v-if="!state.disable">
                    短信将发送至 <strong>{{ state.defaultPhone }}</strong> 请注意查收
                </div>
                <div v-if="state.disable">
                    无法发送短信，请填写个人手机号！
                </div>
            </template>
        </el-alert>
        <el-input
                v-model="state.value"
                :disabled="state.disable"
                clearable
                placeholder="请输入短信验证码"
        >
            <template #append>
                <el-button
                        :disabled="smsApi.smsState.timing!=60 || state.disable"
                        :loading="smsApi.smsState.loading"
                        @click="send">
                    {{ smsApi?.smsState.msg }}
                </el-button>
            </template>
        </el-input>
    </div>

</template>

<script lang="ts">
import {BaseApi} from "~/api/util/BaseService";
import {defineComponent, reactive} from "vue";
import {useUserStore} from "~/store/modulers/user";
import {storeToRefs} from "pinia";

interface Props {
    phone?: string;
    modelValue?: string;
    hideAlter?: boolean;
}


const userStore = useUserStore();
const {user} = reactive(storeToRefs(userStore));

export default defineComponent({
    emits: ["update:modelValue"],
    props: {
        phone: {
            type: String,
        },
        modelValue: {
            type: String,
        },
        hideAlter: {
            type: Boolean,
            default: false,
        },
        defaultPhone: {
            type: String,
            default: user.phone,
        },
    },
    setup: function (props) {

        const state = reactive({
            phone: "",
            defaultPhone: user.phone,
            disable: false,
            value: "",
        });

        class SmsApi extends BaseApi<any> {
            baseUrl: string = "";
        }

        const smsApi = new SmsApi();

        function send() {
            smsApi.sendSmsCode(props.hideAlter ? state.phone : props.defaultPhone);
        }

        return {
            props, state, send, smsApi,
        };
    },
    watch: {
        "state.value"(value) {
            this.$emit("update:modelValue", value);
        },
        "props.phone"(value) {
            if (value) {
                this.state.phone = value;
            }
        },
    },
    mounted() {
        if (!this.props.phone && !user.phone) {
            this.state.disable = true;
        }
    },
});
</script>

<style lang="scss" scoped>

</style>
